// packageA/pages/addSku/index.js
const util = require("./../../../utils/util.js");
Page({

    /**
     * 页面的初始数据
     */
    data: {
        categoryList: [
            { id: 1, name: '推荐' }, { id: 2, name: '奶皮子酸奶' },
            { id: 3, name: '特色口味' }, { id: 4, name: '大杯系列' },
            { id: 5, name: '小杯系列' }, { id: 6, name: '新品上市' },
            { id: 7, name: '优惠套餐' }, { id: 8, name: '酸奶饮品' },
            { id: 9, name: '小吃搭配' }
        ],
        brandIndex: 0,
        category_Id: 0,
        currentCategory: { id: 1, name: '推荐' },
        brandList: [
            { id: 1, name: '草原牧场' }, { id: 2, name: '雪山牦牛' },
            { id: 3, name: '黄金奶源' }
        ],
        // currentBrand: { id: 1, name: '草原牧场' },
        unitList: [
            { id: 1, name: '杯' }, { id: 2, name: '瓶' },
            { id: 3, name: '盒' }, { id: 4, name: '套' }
        ],
        currentUnit: { id: 1, name: '杯' },
        mediaList: ['https://xxg.xjdio.com/images/Zxrh/Product/202510/202512241010184712e676-b296-469a-a817-d638a020f5a6.mp4',],
        mainImage: 'https://xxg.xjdio.com/images/Zxrh/Product/202510/1.jpg',
        goods: {
            title: '奶皮子酸奶', subtitle: '椰香浓郁，口感丝滑', description: '冰爽口感，夏日必备',
            price: '10', memberPrice: '10', stock: '999999', specifications: '500g*1盒',
            isRecommend: false, isNew: false, status: true, brand: '草原牧场'
        }
    },
    categoryChange(e) {
        const index = e.detail.value
        this.setData({
            currentCategory: this.data.categoryList[index],
            category_Id: this.data.categoryList[index].id
        })
    },
    brandChange(e) {
        const index = e.detail.value
        this.setData({
            brandIndex:index,
            'goods.brand': this.data.brandList[index].name
        })
    },
    unitChange(e) {
        const index = e.detail.value
        this.setData({
            currentUnit: this.data.unitList[index]
        })
    },
    test(e) {
        console.log(e.currentTarget.dataset.id);
        debugger
    },
    
    // 删除图片
    removePhoto(e) {
        const _this = this;
        // const index = e.currentTarget.dataset.index;
        var contactstemp = this.data.mainImage;
        // var item=contactstemp[index];
        wx.showModal({
            title: '提示',
            content: '是否确认删除',
            complete: (res) => {
                if (res.cancel) {

                }

                if (res.confirm) {

                    _this.Deletefile(contactstemp).then((res) => {
                        if (res.data) {
                            // contactstemp.splice(index, 1);
                            this.setData({ mainImage: '' });

                        }
                    })
                }
            }
        })

    },
    // 删除轮播图
    removemediaList(e) {
        const _this = this;
        const index = e.currentTarget.dataset.index;
        var contactstemp = this.data.mediaList;
        var item = contactstemp[index];
        wx.showModal({
            title: '提示',
            content: '是否确认删除',
            complete: (res) => {
                if (res.cancel) {

                }

                if (res.confirm) {

                    _this.Deletefile(item).then((res) => {
                        if (res.data) {
                            contactstemp.splice(index, 1);
                            this.setData({ mediaList: contactstemp });

                        }
                    })
                }
            }
        })


    },
    
    Deletefile(param1) {
        return wx.Http.post("/ApiAppService/Xncf.Xxgmall_ApiAppService.Deletefile", {
            DeletePic: param1,

        });
    },
    GetAllCategoriesAsync() {
        return wx.Http.post("/ProductCategoryAppService/Xncf.Xxgmall_ProductCategoryAppService.GetAllCategoriesAsync", {})
    },
    CreateSkuAsync(params) {
        return wx.Http.post("/SkuAppService/Xncf.Xxgmall_SkuAppService.CreateSkuAsync", params)
    },
    chooseMedia(e) {
        console.log(e.currentTarget.dataset.id);
        const _this = this;
        wx.chooseMedia({
            count: 1,
            mediaType: ['image', 'video'],
            sizeType: ["compressed"],//"original",
            sourceType: ["album", "camera"],
            maxDuration: 180,
            success(res) {
                let dt1 = new Date();
                let dt2 = util.formatTime6(dt1);
                let params = {
                    tablename: "Product",
                    tableid: dt2,
                };
                wx.uploadFile({
                    url: wx._baseUrl + "/ApiAppService/Xncf.Xxgmall_ApiAppService.UploadMedia",
                    filePath: res.tempFiles[0].tempFilePath,
                    header: {
                        "content-type": "multipart/form-data",
                        accept: "application/json",
                    },
                    method: "POST",
                    imgType: 1,
                    name: "Zxrh", //文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
                    formData: params, //HTTP 请求中其他额外的 form data
                    success: function (res) {
                        if (res.statusCode == 200) {
                            let datatemp = JSON.parse(res.data);
                            let arr = datatemp.data;//.split(","); //分割数组

                            if (e.currentTarget.dataset.id == 2) {
                                if (e.currentTarget.dataset.index >= 0) {
                                    _this.data.mediaList[e.currentTarget.dataset.index] = arr;
                                } else {
                                    _this.data.mediaList.push(arr)
                                }
                                _this.setData({
                                    mediaList: _this.data.mediaList
                                })
                            } else if (e.currentTarget.dataset.id == 1) {
                                _this.setData({
                                    mainImage: arr
                                })
                            }

                        } else {
                            console.log(res)
                            wx.showToast({
                                title: "上传有误",
                            });
                        }
                    },
                    fail: (err) => {
                        wx.showToast({
                            title: "上传失败!",
                        });
                    },
                });
            },
        });
    },
    previewImage(e) {
        wx.previewImage({
            current: e.currentTarget.dataset.src,
            urls: this.data.mediaList
        })
    },
    toggleRecommend(e) {
        this.setData({
            'goods.isRecommend': e.detail.value
        })
    },
    toggleNew(e) {
        this.setData({
            'goods.isNew': e.detail.value
        })
    },
    toggleStatus(e) {
        this.setData({
            'goods.status': e.detail.value
        })
    },
    submitForm(e) {
        const formData = e.detail.value;
        // debugger
        if (!formData.title) {
            wx.showToast({ title: '请填写商品标题', icon: 'none' })
            return
        }
        if (!this.data.mainImage) {
            wx.showToast({ title: '请上传主图', icon: 'none' })
            return
        }
        if (!formData.specifications) {
            wx.showToast({
                title: '请填写规格', icon: 'none'
            })
            return
        }
        // if (this.data.mediaList.length === 0) {
        //     wx.showToast({ title: '请上传轮播图', icon: 'none' })
        //     return
        // }
        var goods = {
            ...formData,
            category: this.data.currentCategory.name,
            // brand: this.data.currentBrand,
            unit: this.data.currentUnit.name,
            imageUrl: this.data.mainImage,
            mediasUrl: this.data.mediaList.toString(),
            isRecommend: this.data.goods.isRecommend,
            isNew: this.data.goods.isNew,
            status: this.data.goods.status,
            category_Id: this.data.category_Id
            // memberPrice:this.data.memberPrice
        }
        // 指定需要转换为数字的字段
        const numberFields = ['price', 'stock'];
        // 执行转换
        const convertedProduct = this.convertStringToNumber(goods, numberFields);
        console.log('提交数据:', convertedProduct)
        this.CreateSkuAsync(convertedProduct).then((res) => {
            if (res.data) {
                console.log('成功创建产品：', res.data);
                let page = getCurrentPages();
                var prevPage = page[page.length - 2];  //上⼀个页⾯
                prevPage.onLoad();
                setTimeout(() => {
                    wx.navigateBack({
                        delta: 1,
                    });
                }, 500);
                // wx.navigateBack()
            }
        })

    },
    convertStringToNumber(obj, numberFields) {
        // 创建对象的浅拷贝，避免修改原对象
        const result = { ...obj };

        numberFields.forEach(field => {
            if (result.hasOwnProperty(field) && typeof result[field] === 'string') {
                // 尝试转换为数字
                const numValue = parseFloat(result[field]);

                // 如果转换成功且不是NaN，则更新字段值
                if (!isNaN(numValue)) {
                    result[field] = numValue;
                } else {
                    console.warn(`字段 "${field}" 的值 "${result[field]}" 无法转换为数字`);
                }
            }
        });

        return result;
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.GetAllCategoriesAsync().then((res) => {
            if (res.data) {
                this.setData({
                    categoryList: res.data,
                    category_Id: res.data[0].id
                })
            }
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})